package com.biostime.qdingding.modules.job;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.biostime.qdingding.common.config.Global;
import com.biostime.qdingding.common.utils.DateUtils;
import com.biostime.qdingding.common.utils.StringUtils;
import com.biostime.qdingding.modules.job.service.CourseAbsentService;
import com.biostime.qdingding.modules.qd.entity.Course;
import com.biostime.qdingding.modules.qd.entity.CourseOrder;
import com.biostime.qdingding.modules.qd.entity.Siginin;
import com.biostime.qdingding.modules.qd.push.MsgTemplate;
import com.biostime.qdingding.modules.qd.push.MsgTemplate.Absent;
import com.biostime.qdingding.modules.qd.service.CourseOrderService;
import com.biostime.qdingding.modules.qd.service.CourseService;
import com.biostime.qdingding.modules.qd.service.MessageService;
import com.biostime.qdingding.modules.qd.service.SigininService;

/**
 * 上课提醒处理类
 * @author phil
 * @version 2015-12-28
 */
@Service
@Lazy(false)
public class CourseAbsentJob {
	
	@Autowired
	private MessageService messageService;
	@Autowired
	private SigininService sigininService;
	@Autowired
	private CourseOrderService courseOrderService;
	@Autowired
	private CourseAbsentService courseAbsentService;
	@Autowired
	private CourseService courseService;
	
	protected Logger logger = LoggerFactory.getLogger("courseabsent"); //日志对象
	
	private static volatile boolean alive = true; //当前任务是否执行完毕
	private static int limit = 10; //每次读取数据条数
	
	private static long Timeout = 1000*60*60; //任务超时时间(一个小时)
	
	/**
	 * 每天09:00-18:00每个小时执行一次
	 */
	@Scheduled(cron = "0 0 9-18 * * ?")
	//@Scheduled(cron = "*/20 * * * * ?")
	public void schedule(){
		
		Date startOn = new Date();
		
		String flag = Global.getConfig("job.courseabsent");
		if("false".equals(flag) || "0".equals(flag)){
			logger.info(DateUtils.formatDate(startOn, "yyyy-MM-dd HH:mm:ss") + (" 旷课日结--未开启"));
			return;
		}
		
		alive = true;
		logger.info(DateUtils.formatDate(startOn, "yyyy-MM-dd HH:mm:ss") + (" 旷课日结--开始"));
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(Timeout);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				alive = false;
				logger.info(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss") + " 旷课日结--任务超时");
			}
		}).start();
		
		while(alive){
			synchronized (CourseAbsentJob.class) {
				
				new Thread(new Runnable() {
					@Override
					public void run() {
						synchronized (CourseAbsentJob.class) {
						
							List<Map<String,Object>> absentCourses = courseAbsentService.getAbsentCourses(calendar.getTime(), limit);
							if(absentCourses != null && absentCourses.size()>0){
								for(Map<String,Object> row : absentCourses){
									 
									int courseOrderId = StringUtils.toInteger(row.get("courseOrderId"));
									int courseId = StringUtils.toInteger(row.get("courseId"));
									int studentId = StringUtils.toInteger(row.get("studentId"));
									int memberId = StringUtils.toInteger(row.get("memberId"));
									int absentCount = StringUtils.toInteger(row.get("absentCount"));
									
									CourseOrder courseOrder = courseOrderService.get(String.valueOf(courseOrderId));
									Course course = courseService.get(String.valueOf(courseId));
									
									Siginin siginin = new Siginin();
									siginin.setCourseorderId(courseOrderId);
									
									if(courseOrder != null && !sigininService.exist(siginin)){

										sigininService.absent(courseOrder);
										
										//发送签到确认消息
										SimpleDateFormat df = new SimpleDateFormat("MM月dd日");
										String msg = Absent.content;
										msg = msg.replace(MsgTemplate.date, df.format(course.getOndate()));
										msg = msg.replace(MsgTemplate.section, course.getSection());
										msg = msg.replace(MsgTemplate.level, course.getClevel());
										msg = msg.replace(MsgTemplate.serial, course.getSerial());
										msg = msg.replace(MsgTemplate.theme, course.getTheme());
										msg = msg.replace(MsgTemplate.count, String.valueOf(absentCount));
										
										String pushMsg = Absent.push;
										pushMsg = pushMsg.replace(MsgTemplate.date, df.format(course.getOndate()));
										pushMsg = pushMsg.replace(MsgTemplate.section, course.getSection());
										pushMsg = pushMsg.replace(MsgTemplate.level, course.getClevel());
										pushMsg = pushMsg.replace(MsgTemplate.serial, course.getSerial());
										pushMsg = pushMsg.replace(MsgTemplate.theme, course.getTheme());
										pushMsg = pushMsg.replace(MsgTemplate.count, String.valueOf(absentCount));
										
										messageService.sendAndPush(Absent.category, String.valueOf(studentId), Absent.title, msg, String.valueOf(memberId), pushMsg);
									}
								}
							}else{
								alive = false;
							}
							
							CourseAbsentJob.class.notify();
						}
					}
				}).start();
			
				try {
					CourseAbsentJob.class.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
		Date endOn = new Date();
		long time = (endOn.getTime() - startOn.getTime());
		logger.info(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss") + (" 旷课日结--结束") + " 耗时：" + time + " ms");
	}
}
